/************************************************************************************/
/*  Program name CAPAPIMP_AE_HEADERS.sql                                            */
/*  Creater:  WONG Wing Kin (PCCW - UniHub)                                         */
/*************   History   *************************                                */
/* 30 NOV, 2005   WONG Wing Kin         First created                               */
/************************************************************************************/
SET SERVEROUTPUT ON SIZE 1000000;

DECLARE
	lv_Prog_ID		VARCHAR2(100)	:=	'CAPAPIMP_AE_HEADERS';

	lv_Scc_Count	NUMBER			:=	0;
	lv_Err_Count	NUMBER			:=	0;
	lv_Err_Msg		VARCHAR2(500)	:=	'No Error';

	CURSOR Cur_F IS
	SELECT
		*
	FROM
		CRST_AP_AE_HEADERS;

	lv_Next_Seq_ID	NUMBER;

BEGIN

	FOR C1 IN Cur_F LOOP
		BEGIN
			SELECT	AP_AE_HEADERS_S.NextVal
			INTO	lv_Next_Seq_ID
			FROM	DUAL;

			INSERT INTO CRST_AP_AE_HEADERS_MAP VALUES
			(
			C1.AE_HEADER_ID,
			C1.ACCOUNTING_EVENT_ID,
			C1.SET_OF_BOOKS_ID,
			lv_Next_Seq_ID,
			CAPBRIMP_MAPPING.GetAccEventIDMapping(C1.ACCOUNTING_EVENT_ID),
			CAPBRIMP_COMMON.GetSOBID(C1.SOB_SHORT_NAME)
			--CAPBRIMP_MAPPING.GetSOBID(C1.SOB_SHORT_NAME)
			);

			INSERT INTO AP_AE_HEADERS_ALL
			VALUES
			(
			lv_Next_Seq_ID,														--AE_HEADER_ID,
			CAPBRIMP_MAPPING.GetAccEventIDMapping(C1.ACCOUNTING_EVENT_ID),		--ACCOUNTING_EVENT_ID,
			CAPBRIMP_COMMON.GetSOBID(C1.SOB_SHORT_NAME),						--SET_OF_BOOKS_ID,
			C1.AE_CATEGORY,
			C1.CROSS_CURRENCY_FLAG,
			C1.PERIOD_NAME,
			C1.ACCOUNTING_DATE,
			C1.GL_TRANSFER_FLAG,
			C1.GL_TRANSFER_RUN_ID,
			C1.DESCRIPTION,
			CAPBRIMP_COMMON.GetOrgID(C1.ORG_NAME),								--ORG_ID,
			C1.CREATION_DATE,
			CAPBRIMP_COMMON.GetUser(C1.CREATED_BY_NAME),						--CREATED_BY,
			C1.LAST_UPDATE_DATE,
			CAPBRIMP_COMMON.GetUser(C1.LAST_UPDATED_BY_NAME),					--LAST_UPDATED_BY,
			C1.LAST_UPDATE_LOGIN,
			C1.PROGRAM_UPDATE_DATE,
			C1.PROGRAM_APPLICATION_ID,
			C1.PROGRAM_ID,
			C1.REQUEST_ID,
			C1.ACCOUNTING_ERROR_CODE,
			C1.GL_TRANSFER_ERROR_CODE,
			C1.GL_REVERSAL_FLAG,
			C1.TRIAL_BALANCE_FLAG
			);
		EXCEPTION
			WHEN OTHERS THEN
				DBMS_OUTPUT.Put_Line(SQLERRM);
				lv_Err_Count	:=	lv_Err_Count + 1;
		END;
		lv_Scc_Count	:=	lv_Scc_Count	+	1;
	END LOOP;

	IF	lv_Err_Count	>	0	THEN
		ROLLBACK;
	END IF;

	INSERT INTO CAPCNV_LOG(
		PROG_ID,
		PROCESS_DATE,
		RECORD_PROCESSED,
		RECORD_REJECTED,
		RECORD_EXTRACTED,
		ERR_MSG
	) VALUES (
		lv_Prog_ID,
		SYSDATE,
		lv_Scc_Count,
		lv_Err_Count,
		lv_Scc_Count-lv_Err_Count,
		lv_Err_Msg
	);

	COMMIT;
END;
/
